<?php
/**
 * @Entity
 * picture store
 */
class Picture extends EMongoGridFS
{ 
	
	/**
	 * backgroud picture
	 * 1:n
	 */
	const TYPE_PICTURE =0;
	
	/**
	 * user's photot
	 */
	const TYPE_PHOTO =1;
	
	/**
	 * USER'S avatar
	 */
	const TYPE_AVATAR =2;
	
	/**
	 * property
	 */
    public $uid;
    public $type = 0;
   	public $metadata = array();
     
     
    public function __construct($type = self::TYPE_PICTURE){
    	parent::__construct();
    	$this->type = $type;
    }
    /**
     * This method have to be defined in every Model
     * @return string MongoDB collection name, witch will be used to store documents of this model
     */
    public function getCollectionName ()
    {
        return 'pictures';
    }

    public function rules()
    {
        return array(
            array('filename, metadata','safe'),
            array('filename','required'),
            array('metadata','default','value'=>array('type'=>filetype($this->filename)) ,'on'=>'insert'),
        );
    }
 
    /**
     * This method have to be defined in every model, like with normal CActiveRecord
     */
    public static function model ($className = __CLASS__)
    {
        return parent::model($className);
    }
     
    public static function image($uid){
    	$uidObj = new MongoId ($uid);
        $picture = $this->findByAttributes(array('uid'=>$uidObj,'type'=>self::TYPE_PHOTO));
       	return $picture;
    }
    
    public static function insertFromUrl($url,$user_id,$type = self::TYPE_AVATAR){
    	
    	$ext = substr($url,strrpos($url,'.'));
    	if(strlen($ext)>4){
    		$ext = 'jpg';
    	}
    	
    	$cache = Yii::getPathOfAlias("webroot.picture.cache");
    	if(!is_dir($cache)){
        	@mkdir($cache,0777,true);
        }
    	$filename = $cache .'/'. md5($url).'.'.$ext;
    	
    	try{
    		$content = file_get_contents($url);
    		file_put_contents($filename,$content);
    		
    	}catch(Exception $e ){
    		
    	}
    	$picture = new Picture; 
    	$picture->type = $type;
		$picture->filename = $filename;
		$picture->metadata['ext']= $ext;
		$picture->uid = $user_id;
		$picture->save(); 
    	@unlink($filename);
    	return $picture;
    }
    
    protected function beforeSave(){
    	if($this->uid ==null && !Yii::app()->user->isGuest){
    		$this->uid = Yii::app()->user->uid;
    	}
    	return true;
    }
}
?>